package com.atguigu.dga.governance.assessor;

import com.atguigu.dga.governance.bean.AssessParam;
import com.atguigu.dga.governance.bean.GovernanceAssessDetail;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.Date;

public abstract class Assessor {

    public final  GovernanceAssessDetail assess(AssessParam assessParam) {
        //1  初始化考评结果  表名 库名 指标 负责人  异常的处理  创建时间  评分默认10分
        GovernanceAssessDetail governanceAssessDetail = new GovernanceAssessDetail();
        governanceAssessDetail.setTableName(assessParam.getTableMetaInfo().getTableName());
        governanceAssessDetail.setSchemaName(assessParam.getTableMetaInfo().getSchemaName());

        governanceAssessDetail.setMetricId(assessParam.getGovernanceMetric().getId()+"");
        governanceAssessDetail.setMetricName(assessParam.getGovernanceMetric().getMetricName());
        governanceAssessDetail.setGovernanceType(assessParam.getGovernanceMetric().getGovernanceType());

        governanceAssessDetail.setAssessScore(BigDecimal.TEN);
        governanceAssessDetail.setTecOwner(assessParam.getTableMetaInfo().getTableMetaInfoExtra().getTecOwnerUserName());

        governanceAssessDetail.setAssessDate(assessParam.getAssessDate());
        governanceAssessDetail.setCreateTime(new Date());

        //根据白名单来决定是否跳过考评
        String skipAssessTables = assessParam.getGovernanceMetric().getSkipAssessTables();
        if(skipAssessTables!=null){
            String[] skipAssessTableArr = skipAssessTables.split(",");

            for (String skipTableName : skipAssessTableArr) {
                if(skipTableName.equals(assessParam.getTableMetaInfo().getTableName())){
                    governanceAssessDetail.setAssessComment("跳过考评");
                    return governanceAssessDetail;
                }
            }
        }



        //2 检查问题
        try {
            checkProblem(assessParam,governanceAssessDetail);
        }catch (Exception e){
            governanceAssessDetail.setIsAssessException("1");
            //将异常堆栈信息保存字符串中
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            e.printStackTrace(printWriter);
            // 截取前2000个字符
            int endIdx=Math.min(2000,stringWriter.toString().length());
            governanceAssessDetail.setAssessExceptionMsg(stringWriter.toString().substring(0,endIdx));
        }
        return governanceAssessDetail;
    }

    public abstract void checkProblem(AssessParam assessParam,GovernanceAssessDetail governanceAssessDetail) throws  Exception;

}
